package com.ly.gof.create.prototype;

import java.io.*;

/**
 * @author liuyang
 * @des 序列化方式 深克隆
 * @Version 1.0
 * @Date: 20/07/2021 17:27
 */
public class DeepCopySerializable {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        SerialUser serialUser = new SerialUser("李四", new SerialCar("奔驰", "250"));

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(serialUser);

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        SerialUser cloneUser = (SerialUser)ois.readObject();
        System.out.println("serialUser==cloneUser?" + (serialUser == cloneUser));
        System.out.println("serialUser.car==cloneUser.car?" + (serialUser.getSerialCar() == cloneUser.getSerialCar()));
        SerialCar cloneCar = cloneUser.getSerialCar();

        cloneUser.setUsername("张三");
        cloneCar.setCarType("奥迪");
        cloneCar.setCarName("A8");

        System.out.println(serialUser);
        System.out.println(cloneUser);
    }
}

class SerialUser implements Serializable {
    private static final long serialVersionUID = -2167957013938386204L;
    private String username;
    private SerialCar serialCar;

    public SerialUser() {
    }

    public SerialUser(String username, SerialCar serialCar) {
        this.username = username;
        this.serialCar = serialCar;
    }

    @Override
    public String toString() {
        return "SerialUser{" + "username='" + username + '\'' + ", serialCar=" + serialCar + '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public SerialCar getSerialCar() {
        return serialCar;
    }

    public void setSerialCar(SerialCar serialCar) {
        this.serialCar = serialCar;
    }
}

class SerialCar implements Serializable {

    private static final long serialVersionUID = -7308342867043888945L;
    private String carType;
    private String carName;

    public SerialCar() {
    }

    public SerialCar(String carType, String carName) {
        this.carType = carType;
        this.carName = carName;
    }

    @Override
    public String toString() {
        return "SerialCar{" + "carType='" + carType + '\'' + ", carName='" + carName + '\'' + '}';
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }
}
